"""
FastAPI 主应用
ZBlog Python API - MiniMax 文生图服务
"""

import sys
from contextlib import asynccontextmanager
from pathlib import Path

from fastapi import FastAPI, Request, Response
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from loguru import logger

from app.api.routes import ai
from app.core.config import settings


# 配置日志
def setup_logging():
    """配置 loguru 日志"""
    log_file = Path(settings.LOG_FILE)
    log_file.parent.mkdir(parents=True, exist_ok=True)

    # 移除默认处理器
    logger.remove()

    # 添加控制台输出
    logger.add(
        sys.stdout,
        level=settings.LOG_LEVEL,
        format="<green>{time:YYYY-MM-DD HH:mm:ss}</green> | <level>{level: <8}</level> | <cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>",
        colorize=True,
    )

    # 添加文件输出
    logger.add(
        log_file,
        level=settings.LOG_LEVEL,
        format="{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {name}:{function}:{line} - {message}",
        rotation="500 MB",
        retention="10 days",
        compression="zip",
    )


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    # 启动时执行
    setup_logging()
    logger.info(f"启动 {settings.APP_NAME} v{settings.APP_VERSION}")
    logger.info(f"运行环境: {settings.ENVIRONMENT}")
    logger.info(f"调试模式: {settings.DEBUG}")
    logger.info(f"服务地址: http://{settings.HOST}:{settings.PORT}")

    # 检查 MiniMax 配置
    if settings.MINIMAX_DEBUG_MODE:
        logger.info("🔧 MiniMax 调试模式已启用 - 将使用模拟数据")
        logger.info(f"  模拟模型: {settings.MINIMAX_MODEL}")
    else:
        if not settings.MINIMAX_API_KEY:
            logger.warning("⚠️  MiniMax API密钥未配置，文生图功能将不可用")
        else:
            logger.success("✓ MiniMax 生产模式已启用")
            logger.info(f"  API密钥: {settings.MINIMAX_API_KEY[:20]}...")
            logger.info(f"  使用模型: {settings.MINIMAX_MODEL}")

    yield

    # 关闭时执行
    logger.info(f"关闭 {settings.APP_NAME}")


# 创建 FastAPI 应用
app = FastAPI(
    title=settings.APP_NAME,
    version=settings.APP_VERSION,
    description="ZBlog Python API - 提供 MiniMax 文生图服务",
    docs_url="/docs",
    redoc_url="/redoc",
    openapi_url="/openapi.json",
    lifespan=lifespan,
)

# 配置 CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 调试模式：允许所有来源
    allow_credentials=False,  # 当 allow_origins=["*"] 时必须设为 False
    allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
    allow_headers=["*"],
    expose_headers=["*"],
)


# 添加 OPTIONS 请求处理中间件
@app.middleware("http")
async def cors_handler(request: Request, call_next):
    """处理 CORS 预检请求"""
    if request.method == "OPTIONS":
        response = Response()
        response.headers["Access-Control-Allow-Origin"] = "*"
        response.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE, OPTIONS"
        response.headers["Access-Control-Allow-Headers"] = "*"
        response.headers["Access-Control-Max-Age"] = "86400"
        return response
    
    response = await call_next(request)
    return response


# 注册路由
app.include_router(ai.router, prefix="/api/v1")


@app.get("/", tags=["根路径"])
async def root():
    """根路径"""
    return {
        "name": settings.APP_NAME,
        "version": settings.APP_VERSION,
        "status": "running",
        "docs": "/docs",
        "features": ["text-to-image"],
        "providers": ["minimax"],
    }


@app.get("/health", tags=["健康检查"])
async def health():
    """健康检查"""
    return {
        "status": "healthy",
        "version": settings.APP_VERSION,
    }


@app.exception_handler(Exception)
async def global_exception_handler(request, exc):
    """全局异常处理"""
    logger.error(f"未处理的异常: {str(exc)}")
    return JSONResponse(
        status_code=500,
        content={
            "success": False,
            "error": "服务器内部错误",
            "details": str(exc) if settings.DEBUG else None,
        },
    )


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(
        "app.main:app",
        host=settings.HOST,
        port=settings.PORT,
        reload=settings.DEBUG,
        log_level=settings.LOG_LEVEL.lower(),
    )

